import { createElement, HTMLAttributes, type FC } from 'react';
import classNames from 'classnames';
import { accordionTitleDefaultProps } from './defaultProps';
import type { AccordionTitleOptions } from './type';
import { useAccordionContext } from './AccordionContext';

export interface AccordionTitleProps
  extends AccordionTitleOptions,
    Omit<HTMLAttributes<HTMLDivElement>, 'onClick' | 'id'> {}

const AccordionTitle: FC<AccordionTitleProps> = (props) => {
  const { className, active, target, onClick, children, forwardedRef, ...accordionTitleProps } = props;
  const [states, setStates] = useAccordionContext();

  const handleClick = (e: MouseEvent) => {
    if (!states.inTransition) {
      if (states.exclusive) {
        if (states.activeId === target) {
          setStates({ ...states, activeId: undefined, inTransition: true });
        } else {
          setStates({ ...states, activeId: target, inTransition: true });
        }
      } else {
        if (states.activeIds.includes(target)) {
          setStates({
            ...states,
            inTransition: true,
            prevId: target,
            activeIds: states.activeIds.filter((item) => item !== target),
          });
        } else {
          setStates({ ...states, inTransition: true, prevId: target, activeIds: states.activeIds.concat(target) });
        }
      }
    }
    onClick?.(e);
  };

  return createElement(
    'div',
    {
      ref: forwardedRef,
      className: classNames(
        'title',
        { active: active || (states.exclusive ? target === states.activeId : states.activeIds.includes(target)) },
        className,
      ),
      onClick: handleClick,
      ...accordionTitleProps,
    },
    [createElement('i', { key: 'icon', className: 'dropdown icon' }), children],
  );
};

AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle.defaultProps = accordionTitleDefaultProps;

export default AccordionTitle;
